//导出
import * as XLSX from "xlsx";
import request from '@/utils/request'
export const exportTable = {
    data(){
        return{
            enumProps:{}
        }
    },
    methods: {
        getUrl(data, url) {
            return request({
                url: url,
                method: 'post',
                data,
            })
        },
        //导出
        getTableData(data, url, name, type,enumProps = {}) {
            let payload = JSON.parse(JSON.stringify(data))
            payload.limit = 1000
            this.enumProps = enumProps
            if (this.multipleSelection.length == 0) {
                this.getUrl(payload, url, name).then(res => {
                    if (res.code == 200) {
                        this.multipleSelection = type ? res.data.records : res.data.data.records
                        this.multipleSelection.map((item, i) => {
                            item.index = i + 1
                            // item.attribute = this.enumCon.productAttribute(item.attribute)
                            if (item.customFieldVos != null) {
                                item.customFieldVos.map(k => {
                                    item[k.customFieldId] = k.value,
                                        item.customType = k.customFieldMess.fieldType
                                })
                            }
                        })
                        this.exportTable(name, true)
                    }
                })
            } else {
                this.exportTable(name)
            }
        },

        // 导出
        exportTable(n, sta) {
            var that = this;
            let dataArr = this.tableGroup.filter(item => item.label != 'list' && item.type != 'picture')
            import("@/excel/export2Excel").then((excel) => {
                const {
                    export_json_to_excel
                } = require('@/excel/export2Excel'); // 这里必须使用绝对路径，使用@/+存放export2Excel的路径
                let tHeader = dataArr.map(item => {
                    return item.name
                }); // 导出的表头名信息
                let filterVal = dataArr.map(item => {
                    return item.label
                }); // 导出的表头字段名，需要导出表格字段名
                let headerStyle = []
                //拷贝一份数据，不然/****************************************/处会改变列表内数据
                const list = JSON.parse(JSON.stringify(that.multipleSelection)); 
                let check = dataArr.find(res => {
                    return res.type == 'selectChecked'
                })
                if (check != undefined) {
                    list.map((item, i) => {
                        if (item[check.label]) {
                            try {
                                item[check.label] = JSON.parse(item[check.label]).join(',')
                            } catch {

                            }
                        }
                    })
                }
                list.map(item => {
                    //关联单据
                    if(item.relatedSalesInfoVo) item.relatedSalesInfoVo = item.relatedSalesInfoVo.salesCode
                    item.attribute !== undefined ? item.attribute = this.enumCon.productAttribute(item.attribute) : ''
                    /****************************************/
                    Object.keys(item).forEach(i => {
                        for (const key in this.enumProps) {
                            if (i == key) item[i] = this.enumProps[key][item[i]]
                        }
                    })
                    if (item.vos) {
                        let d = item.vos;
                        let str = []
                        d.map(j => {
                            str.push(j.name)
                        })
                        item.vos = str.join(',')
                    }
                })
                const data = that.formatJson(filterVal, list);
                var sheet = XLSX.utils.json_to_sheet(data, {
                    skipHeader: true,
                });
                for (const key in sheet) {
                    // 第一行，表头
                    if (key.replace(/[^0-9]/ig, '') === '1') {
                        headerStyle.push(key)
                    }
                }
                excel.export_json_to_excel2({
                    header: tHeader,
                    data,
                    filename: n,
                    headerStyle
                }); // 导出的表格名称，根据需要自己命名

                if (sta) {
                    this.multipleSelection = []
                }
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
    }
}


//自定义列表拖拽
import {
    fieldList,
    pageColumnSort
} from '@/api/customFieldController'
import Sortable from "sortablejs"
import { Object } from "core-js"
export const customSortTable = {
    mounted() {
        this.getFieldList(this.searchForm)
        // 阻止默认行为
        document.body.ondrop = function (e) {
            e.preventDefault()
            e.stopPropagation()
        };
        this.rowDrop()
    },
    methods: {
        //自定义字段列表
        getFieldList(data) {
            this.loading = true
            fieldList(data).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.records.sort((a, b) => b.sort - a.sort)
                    this.total = res.data.total
                    this.$emit('getTotal', res.data.total)
                }
                this.loading = false
            })
        },
        //拖拽列表
        getPageColumnSort(data) {
            pageColumnSort(data).then(res => {
                if (res.code == 200) {
                    this.getFieldList(this.searchForm)
                }
            })
        },

        //行拖拽
        rowDrop() {
            const tbody = document.querySelector(".el-table__body-wrapper tbody")
            const _this = this
            Sortable.create(tbody, {
                animation: 150,
                onEnd({
                    newIndex,
                    oldIndex
                }) {
                    let sortTable = []
                    const currRow = _this.tableData.splice(oldIndex, 1)[0]
                    _this.tableData.splice(newIndex, 0, currRow)
                    sortTable = _this.tableData.map((i, index) => {
                        return {
                            id: i.id,
                            sort: _this.tableData.length - index
                        }
                    })
                    _this.getPageColumnSort({
                        customFields: sortTable
                    })
                }
            })
        },
    }
}


//移动端卡片设置
import {
    columnDropDown,
    cardSetEdit,
    cardSetDetail
} from '@/api/produceController'
export const h5CardSet = {
    data(){
        var titleValues = (rule, value, callback) => {
            if (!value.length) {
                return callback(new Error('标题不能为空！'));
            } else if(value.length>5){
                return callback(new Error('最多支持5个'))
            } else {
                callback()
            }
        };
        return {
            cardSetForm:{
                titleValues:[],
                coverValue:'不展示',
                columnValues:[]
            },
            cardSetRules:{
                titleValues: [{
                    required: true,
                    validator:titleValues,
                    trigger:'change'
                }],
                coverValue: [{
                    required: true
                }],
                columnValues: [{
                    required: true,
                    message:'展示字段不能为空！'
                }],
            },
            coverValueOptions:[{
                cnName: "不展示",
                columnModule: "workOrder",
                fieldType: null
            }],
            module:'',
            cardSetDrawer:false,
            titleValuesOptions:[],
            columnValuesOptions:[],
            checkAll:false,
            isIndeterminate: false,
            checkedField:[],
            cardSetLoading:false,
            fields:[],
            dataColumns:[]
        }
    },
    mounted() {
    },
    methods:{
        //获取模块字段下拉
        getColumnDropDown(data) {
            this.cardSetLoading = true
            columnDropDown(data).then(res => {
                if(res.code == 200){
                    this.dataColumns = res.data.columns
                    this.titleValuesOptions = res.data.columns
                    this.coverValueOptions = [...this.coverValueOptions,...res.data.pictureColumns]
                    this.columnValuesOptions = res.data.columns
                    this.fields = res.data.columns.map(i => i.cnName)
                    this.getCardSetDetail({belongModule:this.module == 'workOrder' ? 0 : 1})
                }
                this.cardSetLoading = false
            })
        },
        //卡片保存
        getCardSetEdit(data) {
            cardSetEdit(data).then(res => {
                if(res.code == 200){
                    this.utils.showMsg('配置修改成功','success')
                    this.cardSetDrawer = false
                }
            })
        },
        //卡片详情
        getCardSetDetail(data) {
            cardSetDetail(data).then(res => {
                if(res.code == 200){
                   this.cardSetForm.titleValues = res.data.titleValues
                   res.data.coverValue && (this.cardSetForm.coverValue = res.data.coverValue)
                   this.cardSetForm.columnValues = res.data.columnValues
                   this.checkedField = res.data.columnValues
                   this.checkAll = res.data.columnValues.length === this.fields.length
                }
            })
        },
        //打开卡片
        cardHandle(module){
            this.cardSetDrawer = true
            this.module = module
            this.getColumnDropDown(module)
        },
        //展示字段改变
        fieldChange(fieldArr){
            this.checkedField = fieldArr
        },
        handleCheckAllChange(val) {
            this.checkedField = val ? this.fields : []
            this.cardSetForm.columnValues = val ? this.fields : []
            this.isIndeterminate = false
        },
        handleCheckedCitiesChange(value) {
            this.cardSetForm.columnValues = value
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.fields.length
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.fields.length
        },
        //关闭卡片
        cardSetClose(){
            this.$refs.cardSetForm.resetFields()
            this.checkedField = []
            this.checkAll = false
            this.coverValueOptions = [{
                cnName: "不展示",
                columnModule: "workOrder",
                fieldType: null
            }]
        },
        //卡片设置保存
        saveCardSet(module){
            this.$refs.cardSetForm.validate((valid) => {
                if (valid) {
                    let columns = {} , cover = '' , titles = {} , payload = {}
                    columns = this.dataColumns.filter(i => this.cardSetForm.columnValues.indexOf(i.cnName) != -1)
                    cover = this.coverValueOptions.find(i => this.cardSetForm.coverValue == i.cnName)
                    titles = this.dataColumns.filter(i => this.cardSetForm.titleValues.indexOf(i.cnName) != -1)
                    payload = Object.assign({columns},{cover},{titles},{belongModule:module.belongModule})
                    this.getCardSetEdit(payload)
                } else {
                    return false
                }
            })
        }
    }
}